package Rservetest.Rservetest;

import java.util.Properties;

import org.math.R.RserveSession;
import org.math.R.RserverConf;
import org.math.R.Rsession;
import org.math.R.Rsession.RException;

public class HaModelLoad {
	public static void main(String args[]) throws RException {
		//远程R服务器应该有权限读取数据库!!!!并且安装好GDAL,proj4和GEOS开源GIS库，有权限安装R包
		//远程R服务器运行Rserve::Rserve(args=' --no-restore --no-save --slave --RS-enable-remote',quote=F)
		RserverConf rconf = new RserverConf("10.10.10.56", 6311, "", "", new Properties());		
		Rsession s = null;
		s = RserveSession.newRemoteInstance(System.out, rconf);
		s.voidEval("library(gwr.avm)");   //加载package
		s.voidEval("install.dependencies()"); //安装依赖
		//		# 保存路径，默认为'./models.avm'
		s.voidEval("model.path<-model.store.path('/tmp/avm')");	
		//		String txt = (String)s.eval("list.files(model.path)");
		//		System.out.println(txt);
		//		        # 模型读取
		s.voidEval("avm.models.2<-avm.model.restore(city_code='bj',"
				+ "yearmonth = '2017-7',"
				+"avm.model.store.path='./save',"
				+ "proptype = '11',dependentY = 'rentprice')");
		s.voidEval("model.path<-getOption('avm.model.store.path')");
		//	    # 读取数据
		s.voidEval("tabln.vec <- readRDS(file.path(model.path,"
				+ "paste('bj','2017-7','tabha.rds',sep='_')))");
		s.voidEval("poi.data.list <- readRDS(file.path(model.path,"
				+ "paste('bj','2017-7','poiha.rds',sep='_')))");
		//   # 生成未知预测数据,可以任意给城市内的一个位置
		///////////////////////////////////////////////////////////////
		///////////////////////////////////////////////////////////////
		s.voidEval("pred.xy<-avm.pred.data(train.models = avm.models.2,"
				+ "x=116.4411,y=39.848,"+
				", proptype = '11', bldg_code = '11', bldg_area = 80, br = 2, buildyear=2017,"
				+"tabln.vec = tabln.vec,poi.data.list = poi.data.list)");	                               
		//# 用读取的模型再次预测
		s.voidEval("pred<-avm.pred(train.models=avm.models.2,"
				+ "newdata=pred.xy,remove.dup = T," + 
				" model.list =list(ols = T, rlm = T,svm = T, "
				+ "rft = T, gwr1 = F, xgb = T) )");
		double[] pred =(double[]) s.eval("(pred%>%as.numeric())[-c(1,2)]%>%exp"); //create java variable from R command
		for(double val:pred){
			System.out.print(val+",");
		}
		s.close();
	}	
}
